package admin

import (
	"fmt"
	"net/http"
	"shop/internal/models"
	"shop/internal/service/new_article_service"
	"shop/pkg/app"
	"shop/pkg/constant"
	"shop/pkg/global"
	"shop/pkg/util"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

// 新闻api
type NewArticleController struct {
}

// @Title 文章详情
func (e *NewArticleController) Get(c *gin.Context) {
	var (
		appG = app.Gin{C: c}
	)
	id := com.StrTo(c.Param("id")).MustInt64()
	global.LOG.Info(id)
	newArticleService := new_article_service.NewArticle{Id: id}

	vo := newArticleService.Get()
	appG.Response(http.StatusOK, constant.SUCCESS, vo)
}

// @Title 文章列表
// @Description 文章列表
// @Success 200 {object} app.Response
// @router / [get]

func (e *NewArticleController) GetAll(c *gin.Context) {
	var (
		appG = app.Gin{C: c}
	)
	isDel := com.StrTo(c.DefaultQuery("is_del", "0")).MustInt()
	//isPub := com.StrTo(c.DefaultQuery("is_pub", "1")).MustInt()
	title := c.DefaultQuery("title", "")
	newarticleService := new_article_service.NewArticle{
		IsDel:    isDel,
		Title:    title,
		PageSize: util.GetSize(c),
		PageNum:  util.GetPage(c),
	}
	vo := newarticleService.GetAll()
	appG.Response(http.StatusOK, constant.SUCCESS, vo)

}

// 添加新闻
func (e *NewArticleController) Post(c *gin.Context) {
	var (
		appG  = app.Gin{C: c}
		model models.NewArticle
	)
	paramsErr := app.BindAndValidate(c, &model)
	if paramsErr != nil {
		appG.Response(http.StatusBadRequest, paramsErr.Error(), nil)
		return
	}

	newArticleService := new_article_service.NewArticle{
		M: &model,
	}
	if err := newArticleService.Insert(); err != nil {
		appG.Response(http.StatusInternalServerError, constant.FAIL_ADD_DATA, nil)
	}
	appG.Response(http.StatusOK, constant.SUCCESS, nil)

}

// 编辑新闻
func (e *NewArticleController) Put(c *gin.Context) {
	var (
		appG  = app.Gin{C: c}
		model models.NewArticle
	)
	httpCode, errCode := app.BindAndValid(c, &model)
	if errCode != constant.SUCCESS {
		appG.Response(httpCode, errCode, nil)
		return
	}
	newArticleService := new_article_service.NewArticle{
		M: &model,
	}

	if err := newArticleService.Save(); err != nil {
		appG.Response(http.StatusInternalServerError, constant.FAIL_ADD_DATA, nil)
	}
	appG.Response(http.StatusOK, constant.SUCCESS, nil)

}

// 删除新闻
func (e *NewArticleController) Delete(c *gin.Context) {
	var (
		ids  []int64
		appG = app.Gin{C: c}
	)

	id := com.StrTo(c.Param("id")).MustInt64()
	ids = append(ids, id)
	fmt.Println(ids)
	newArticleService := new_article_service.NewArticle{Ids: ids}
	if err := newArticleService.Delete(); err != nil {
		appG.Response(http.StatusInternalServerError, constant.FAIL_ADD_DATA, nil)
	}

	appG.Response(http.StatusOK, constant.SUCCESS, nil)
}
